<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yuanzhiying.github.io","root":"/","images":"/images","scheme":"Gemini","version":"8.1.0","exturl":false,"sidebar":{"position":"right","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":true,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="学习文章：SwiftUI对比Flutter八个常见的SwiftUI误用及对应的正确打开方式SwiftUI 基础之 IdentifiableSwiftUI - Data Binding注解  SwiftUI要求   iOS13.0+  快捷键 control + option + 点击：出现属性编辑器 command + 点击：出现快捷菜单  布局 VStack - 垂直布局 HStack - 水平">
<meta property="og:type" content="article">
<meta property="og:title" content="SwiftUI学习">
<meta property="og:url" content="http://yuanzhiying.github.io/2021/01/14/SwiftUI%E5%AD%A6%E4%B9%A0/index.html">
<meta property="og:site_name" content="yuanzhiying的博客">
<meta property="og:description" content="学习文章：SwiftUI对比Flutter八个常见的SwiftUI误用及对应的正确打开方式SwiftUI 基础之 IdentifiableSwiftUI - Data Binding注解  SwiftUI要求   iOS13.0+  快捷键 control + option + 点击：出现属性编辑器 command + 点击：出现快捷菜单  布局 VStack - 垂直布局 HStack - 水平">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-01-14T01:51:25.000Z">
<meta property="article:modified_time" content="2021-01-26T05:52:41.209Z">
<meta property="article:author" content="yuanzhiying">
<meta property="article:tag" content="Swift">
<meta property="article:tag" content="SwiftUI">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://yuanzhiying.github.io/2021/01/14/SwiftUI%E5%AD%A6%E4%B9%A0/">


<script data-pjax class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>SwiftUI学习 | yuanzhiying的博客</title>
  



  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="yuanzhiying的博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">yuanzhiying的博客</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">工作学习记录</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">4</span></a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">7</span></a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">9</span></a></li>
        <li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <section class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-6"><a class="nav-link" href="#%E5%BF%AB%E6%8D%B7%E9%94%AE"><span class="nav-number">1.</span> <span class="nav-text">快捷键</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#%E5%B8%83%E5%B1%80"><span class="nav-number">2.</span> <span class="nav-text">布局</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#%E4%BB%A3%E7%A0%81%E8%A7%A3%E6%9E%90"><span class="nav-number">3.</span> <span class="nav-text">代码解析</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E6%8A%80%E5%B7%A7"><span class="nav-number">4.</span> <span class="nav-text">使用技巧</span></a></li></ol></div>
        </section>
        <!--/noindex-->

        <section class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">yuanzhiying</p>
  <div class="site-description" itemprop="description">坚持下去</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">9</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">4</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/yuanzhiying" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;yuanzhiying" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>



        </section>
      </div>
        <div class="back-to-top animated">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yuanzhiying.github.io/2021/01/14/SwiftUI%E5%AD%A6%E4%B9%A0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="yuanzhiying">
      <meta itemprop="description" content="坚持下去">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="yuanzhiying的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          SwiftUI学习
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-01-14 09:51:25" itemprop="dateCreated datePublished" datetime="2021-01-14T09:51:25+08:00">2021-01-14</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-01-26 13:52:41" itemprop="dateModified" datetime="2021-01-26T13:52:41+08:00">2021-01-26</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Swift/" itemprop="url" rel="index"><span itemprop="name">Swift</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
      </div>
      <div class="post-meta">
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>6.6k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>6 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>学习文章：<br><a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_33701617/article/details/93164551?utm_medium=distribute.pc_relevant.none-task-blog-searchFromBaidu-2.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-searchFromBaidu-2.control">SwiftUI对比Flutter</a><br><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/343549752">八个常见的SwiftUI误用及对应的正确打开方式</a><br><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/8d5e0f80856b">SwiftUI 基础之 Identifiable</a><br><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/a2a69fb070b0">SwiftUI - Data Binding注解</a></p>
<ul>
<li><code>SwiftUI</code>要求</li>
</ul>
<ol>
<li>iOS13.0+</li>
</ol>
<h6 id="快捷键"><a href="#快捷键" class="headerlink" title="快捷键"></a>快捷键</h6><ol>
<li>control + option + 点击：出现属性编辑器</li>
<li>command + 点击：出现快捷菜单</li>
</ol>
<h6 id="布局"><a href="#布局" class="headerlink" title="布局"></a>布局</h6><ol>
<li>VStack - 垂直布局</li>
<li>HStack - 水平布局</li>
<li>Spacer - 间距</li>
<li>Text - 文本</li>
<li>Image - 图片</li>
<li>Divider - 分割线</li>
<li>Group - 预览窗口预览多个</li>
<li>ScrollView - 滚动视图</li>
<li>Path - 路径</li>
<li>Shaper - 形状</li>
</ol>
<h6 id="代码解析"><a href="#代码解析" class="headerlink" title="代码解析"></a>代码解析</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">struct ContentView: View &#123;</span><br><span class="line">    var body: some View &#123;</span><br><span class="line">        Text(&quot;Hello, world!&quot;)</span><br><span class="line">            .font(.title)</span><br><span class="line">            .foregroundColor(.yellow)</span><br><span class="line">            .bold()</span><br><span class="line">            .italic()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">struct ContentView_Previews: PreviewProvider &#123;</span><br><span class="line">    static var previews: some View &#123;</span><br><span class="line">        ContentView()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol>
<li><code>ContentView</code>为布局，<code>ContentView_Previews</code>为预览布局</li>
<li><code>body</code>为计算属性，类型为不透明类型的<code>View</code>，不透明类型使用<code>some</code>修饰</li>
<li><code>Swift</code>语法，只有一行代码，<code>return</code>可以省略</li>
<li><code>some</code>修饰，表示不透明类型，总会返回某一个特定的类型，但是不知道是哪一种<blockquote>
<ol>
<li>可以返回关联类型的协议类型</li>
<li>安全性：不对外暴露具体的返回类型</li>
<li>用来解决<code>SwiftUI</code>繁琐的不确定返回类型问题</li>
</ol>
</blockquote>
</li>
</ol>
<h6 id="使用技巧"><a href="#使用技巧" class="headerlink" title="使用技巧"></a>使用技巧</h6><ol>
<li><p>可以在右上角+里拖动空间到代码中</p>
</li>
<li><p>使用<code>import</code>导入所需的库</p>
</li>
<li><p>可以新建<code>SwiftUI View</code></p>
</li>
<li><p><code>ignoresSafeArea</code>忽略<code>safeArea</code>的边距，用在<code>feame</code>前</p>
</li>
<li><p>布局group组件可增加<code>padding</code></p>
</li>
<li><p><code>VStack</code>可添加<code>font</code>、<code>foregroundColor</code>等属性，对所有包含的元素起效</p>
</li>
<li><p>串联属性，每一个点语法属性，返回当前对象</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Text(&quot;Hello world!&quot;)</span><br><span class="line">   .font(.title)</span><br><span class="line">   .foregroundColor(.purple)</span><br><span class="line">   </span><br><span class="line">A modifier returns a view that applies a new behavior or visual change. You can chain multiple modifiers to achieve the effects you need.</span><br></pre></td></tr></table></figure></li>
<li><p>使用<code>previewLayout</code>可以定义预览的窗口的大小，也可以使用<code>Group</code>同时预览多个窗口，通用属性可以提取到外面</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">struct LandmarkRow_Previews: PreviewProvider &#123;</span><br><span class="line">    static var previews: some View &#123;</span><br><span class="line">        Group &#123;</span><br><span class="line">            LandmarkRow(landmark: landmarks[0])</span><br><span class="line">            LandmarkRow(landmark: landmarks[1])</span><br><span class="line">        &#125;</span><br><span class="line">        .previewLayout(.fixed(width: 300, height: 70))</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p><code>Identifiable</code>：作为唯一标识<br>遍历需要唯一标识来遍历，如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">List(landmarks, id: \.id) &#123; landmark in</span><br><span class="line">    NavigationLink(</span><br><span class="line">        destination: LandmarkDetail()) &#123;</span><br><span class="line">        LandmarkRow(landmark: landmark)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果让列表中元素遵守<code>Identifiable</code>协议，遍历处即可省略<code>id</code>参数，model中需要有名称为<code>id</code>的属性</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">struct Landmark: Hashable, Codable, Identifiable &#123;</span><br><span class="line">    var id: Int</span><br><span class="line">    var name: String</span><br></pre></td></tr></table></figure></li>
<li><p>页面跳转使用<code>NavigationLink</code>，<code>destination</code>为要跳转的页面</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">NavigationLink(destination: LandmarkDetail()) &#123;</span><br><span class="line">    LandmarkRow(landmark: landmark)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>使用<code>NavigationView</code>为页面田健导航栏，可设置 <code>navigationTitle</code>等</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">NavigationView &#123;</span><br><span class="line">    List(landmarks) &#123; landmark in</span><br><span class="line">        NavigationLink(destination: LandmarkDetail()) &#123;</span><br><span class="line">            LandmarkRow(landmark: landmark)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    .navigationTitle(&quot;Landmarks&quot;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>预览窗口按钮作用：<br>第一个按钮：<code>Live Preview</code> 和<code>Debug Preview</code>，未打开只能查看页面，不能点击等，打开之后可以点击跳转页面等交互操作<br>第二个按钮：<code>Preview On Device</code>，连上真机点击之后，预览可以同步在真机上展示<br>第三个按钮：<code>Inspect Preview</code>，可以打开窗口属性窗口，可以设置预览窗口属性<br>第四个按钮：<code>Duplicate Preview</code> ，可以复制创建多个预览窗口</p>
</li>
<li><p>代码控制预览的机型</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">struct LandmarkList_Previews: PreviewProvider &#123;</span><br><span class="line">    static var previews: some View &#123;</span><br><span class="line">        LandmarkList()</span><br><span class="line">            .previewDevice(PreviewDevice(rawValue: &quot;iPhone SE (2nd generation)&quot;))</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 多设备同时预览</span><br><span class="line">struct LandmarkList_Previews: PreviewProvider &#123;</span><br><span class="line">    static var previews: some View &#123;</span><br><span class="line">        ForEach([&quot;iPhone 8&quot;, &quot;iPhone 12 Pro Max&quot;], id: \.self) &#123; deviceName in</span><br><span class="line">            LandmarkList()</span><br><span class="line">                .previewDevice(PreviewDevice(rawValue: deviceName))</span><br><span class="line">                .previewDisplayName(deviceName)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>组合静态的<code>View</code>和动态的<code>view</code>到<code>List</code>里，可使用<code>List + ForEach</code>：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">List(filteredLandmarks) &#123; landmark in</span><br><span class="line">    NavigationLink(destination: LandmarkDetail(landmark: landmark)) &#123;</span><br><span class="line">        LandmarkRow(landmark: landmark)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">替换为</span><br><span class="line"></span><br><span class="line">List &#123;</span><br><span class="line">    Toggle(isOn: $showFavoriteOnly) &#123;</span><br><span class="line">        Text(&quot;Favorites only&quot;)</span><br><span class="line">    &#125;</span><br><span class="line">    ForEach(filteredLandmarks) &#123; landmark in</span><br><span class="line">        NavigationLink(destination: LandmarkDetail(landmark: landmark)) &#123;</span><br><span class="line">            LandmarkRow(landmark: landmark)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果遍历的对象没有实现<code>Identifiable</code>协议，则需要传<code>id</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">List &#123;</span><br><span class="line">    ForEach(modelData.categories.keys.sorted(), id: \.self) &#123; key in</span><br><span class="line">        Text(key)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p><code>ObservableObject</code>协议<br>当遵守<code>ObservableObject</code>协议的数据更新时，绑定数据的<code>view</code>会自动更新</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">final class ModelData: ObservableObject &#123;</span><br><span class="line">    @Published var landmarks: [Landmark] &#x3D; load(&quot;landmarkData.json&quot;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p><code>@Published</code><br>使用<code>@Published</code>修饰监听对象的属性，表示该对象的属性需要把属性值的改变更新进去</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">final class ModelData: ObservableObject &#123;</span><br><span class="line">    @Published var landmarks: [Landmark] &#x3D; load(&quot;landmarkData.json&quot;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p><code>@StateObject</code><br>使用<code>@StateObject</code>初始化一个监听对象的数据，<br>使用<code>.environmentObject</code>把数据设置到环境对象里，<br>在需要的地方去取环境对象<code>@EnvironmentObject var modelData: ModelData</code>进行使用</p>
</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">@main</span><br><span class="line">struct MySwiftUIApp: App &#123;</span><br><span class="line">    &#x2F;&#x2F; 定义</span><br><span class="line">    @StateObject private var modelData &#x3D; ModelData()</span><br><span class="line">    </span><br><span class="line">    var body: some Scene &#123;</span><br><span class="line">        WindowGroup &#123;</span><br><span class="line">            ContentView()</span><br><span class="line">            &#x2F;&#x2F; 设置</span><br><span class="line">                .environmentObject(modelData)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 取</span><br><span class="line">@EnvironmentObject var modelData: ModelData</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 使用</span><br><span class="line">modelData.landmarks</span><br></pre></td></tr></table></figure>
<ol start="18">
<li><code>Bool</code>的<code>toggle()</code>方法：在<code>true</code>和<code>false</code>之前切换</li>
<li><code>@EnvironmentObject</code>属性用于在下级view中接收传递过来的参数</li>
<li><code>environmentObject(_:) </code>方法用于向下级传递参数</li>
<li><code>@Binding</code>：绑定修饰符用于修饰一个值，这个值用来改变另外一个值<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">绑定：</span><br><span class="line">@Binding var isSet: Bool</span><br><span class="line"></span><br><span class="line">修改：</span><br><span class="line">FavoriteButton(isSet: $modelData.landmarks[landmarkIndex].isFavorite)</span><br></pre></td></tr></table></figure></li>
<li>定义有状态的字段，使用<code>@State</code>修饰，定义为<code>private</code>，并且赋初始值<br><code>@State private var showFavoritesOnly = false</code></li>
<li><code>@State</code>：<br>使用@State属性为应用程序中的数据建立一个真实来源，您可以从多个视图中修改这些数据。SwiftUI管理底层存储并根据值自动更新视图。</li>
<li>使用<code>Path</code>直接绘制，可以当做View来使用</li>
<li><code>View</code>动画，包括颜色、透明度、旋转、大小和其他属性等，可以使用<code>withAnimation</code>来包裹状态State实现动画<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">withAnimation &#123;</span><br><span class="line">    self.showDetail.toggle()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">withAnimation(.easeInOut(duration: 4)) &#123;</span><br><span class="line">    self.showDetail.toggle()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>调用<code>View</code>的<code>transition</code>可以为<code>View</code>添加动画<br><code>HikeDetail(hike: hike).transition(.slide)</code><br>自定义<code>transition</code>可自定义动画<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">extension AnyTransition &#123;</span><br><span class="line">    static var moveAndFade: AnyTransition &#123;</span><br><span class="line">        AnyTransition.slide</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">extension AnyTransition &#123;</span><br><span class="line">    static var moveAndFade: AnyTransition &#123;</span><br><span class="line">        AnyTransition.move(edge: .trailing)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">extension AnyTransition &#123;</span><br><span class="line">    static var moveAndFade: AnyTransition &#123;</span><br><span class="line">        let insertion &#x3D; AnyTransition.move(edge: .trailing).combined(with: .opacity)</span><br><span class="line">        let removal &#x3D; AnyTransition.scale.combined(with: .opacity)</span><br><span class="line">        return .asymmetric(insertion: insertion, removal: removal)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><code>ListRowInsets</code>用来调整一个view在lsit中的上下左右间距</li>
<li><code>CaseIterable</code>，用在<code>enum</code>中用来获取<code>allCases</code>方法</li>
<li><code>@Environment</code>，SwiftUI提供了在环境中值的存储，使用<code>@Environment</code>可以访问值，并可以读写<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">@Environment(\.editMode) var editMode</span><br></pre></td></tr></table></figure></li>
<li><code>@State</code> 、<code>@ObservableObject</code>、<code>@Binding</code>、<code>@EnvironmentObject</code>区别<br>@State和@ObservableObject之间有一些细微的差异。这些都是很重要的，因为它们都有不同的用途。<br>@State在视图本地。值或数据在视图中本地保存。它由框架管理，由于它存储在本地，因此它是一个值类型。<br>@ObservableObject在视图外部，并且不存储在视图中。它是一种引用类型，因为它不在本地存储，而只是具有对该值的引用。这不是由框架自动管理的，而是开发人员的责任。这最适用于外部数据，例如数据库或由代码管理的模型。<br>@Binding也在视图内，但是与@State区别在于@Binding用于不通视图之间的参数传递。@Binding和@ObservedObbjecg一样都是传递引用。<br>@EnvironmentObject 可以理解为全局变量</li>
<li><code>ObservableObject</code>和<code>@Published</code><br>遵循 ObservableObject 协议的类可以使用 SwiftUI 的 @Published 属性包装器来自动发布属性的变化，以便使用该类的实例的任何视图能够自动重新调用 body 属性，保持界面与数据的一致。<br><code>@Published var profile = Profile.default</code><br>界面中使用<code>@Binding</code>来绑定UI<br>``</li>
<li>使用<code>UIViewRepresentable</code>来将<code>UIKit</code>中已有的<code>View</code>在<code>SwiftUI</code>中使用<br>使用<code>UIViewControllerRepresentable</code>来<code>UIKit</code>中的<code>UIViewController</code>在<code>SwiftUI</code>中使用<br><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/384867321b67">UIViewRepresentable</a><br>使用方法如下：<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">import SwiftUI</span><br><span class="line">import UIKit</span><br><span class="line"></span><br><span class="line">struct PageControl: UIViewRepresentable &#123;</span><br><span class="line">    var numberOfPages: Int</span><br><span class="line">    @Binding var currentPage: Int</span><br><span class="line">    </span><br><span class="line">    func makeUIView(context: Context) -&gt; UIPageControl &#123;</span><br><span class="line">        let control &#x3D; UIPageControl()</span><br><span class="line">        control.numberOfPages &#x3D; numberOfPages</span><br><span class="line">        return control</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    func updateUIView(_ uiView: UIPageControl, context: Context) &#123;</span><br><span class="line">        uiView.currentPage &#x3D; currentPage</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>

    </div>

    
    
    
      
  <div class="popular-posts-header">相关文章</div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="/2021/01/13/SwiftUI-中的some关键字/" rel="bookmark">SwiftUI 中的some关键字</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="/2021/01/26/Swift中associatedtype/" rel="bookmark">Swift中associatedtype</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="/2021/01/22/SwiftUI与原项目混用/" rel="bookmark">SwiftUI与原项目混用</a></div>
    </li>
  </ul>


    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>yuanzhiying
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="http://yuanzhiying.github.io/2021/01/14/SwiftUI%E5%AD%A6%E4%B9%A0/" title="SwiftUI学习">http://yuanzhiying.github.io/2021/01/14/SwiftUI学习/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/Swift/" rel="tag"><i class="fa fa-tag"></i> Swift</a>
              <a href="/tags/SwiftUI/" rel="tag"><i class="fa fa-tag"></i> SwiftUI</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/01/13/SwiftUI-%E4%B8%AD%E7%9A%84some%E5%85%B3%E9%94%AE%E5%AD%97/" rel="prev" title="SwiftUI 中的some关键字">
                  <i class="fa fa-chevron-left"></i> SwiftUI 中的some关键字
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/01/22/SwiftUI%E4%B8%8E%E5%8E%9F%E9%A1%B9%E7%9B%AE%E6%B7%B7%E7%94%A8/" rel="next" title="SwiftUI与原项目混用">
                  SwiftUI与原项目混用 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2020 – 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yuanzhiying</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">16k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">14 分钟</span>
  </span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/@next-theme/pjax@0.4.0/pjax.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/next-boot.js"></script><script src="/js/bookmark.js"></script><script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '.page-configurations',
    '.main-inner',
    '.post-toc-wrap',
    '.languages',
    '.pjax'
  ],
  analytics: false,
  cacheBust: false,
  scrollRestoration: false,
  scrollTo: !CONFIG.bookmark.enable
});

document.addEventListener('pjax:success', () => {
  pjax.executeScripts(document.querySelectorAll('script[data-pjax], .pjax script'));
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  const hasTOC = document.querySelector('.post-toc');
  document.querySelector('.sidebar-inner').classList.toggle('sidebar-nav-active', hasTOC);
  document.querySelector(hasTOC ? '.sidebar-nav-toc' : '.sidebar-nav-overview').click();
  NexT.utils.updateSidebarPosition();
});
</script>


  

<script src="/js/local-search.js"></script>






  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>




    <div class="pjax">


    </div>
</body>
</html>
